package com.yang.staff.websocket;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yang.staff.controller.StaffController;
import com.yang.staff.service.StaffService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint("/immediateChat")
public class ImmediateChat {

    @Autowired
    private static StaffService staffService;

    @Autowired
    public void setChatService(StaffService  staffService) {
        ImmediateChat.staffService = staffService;
    }
    private static Map<String, Session> chatMap = new ConcurrentHashMap<String, Session>();


    /**
     * 页面和通道第一次建立连接触发
     */
    @OnOpen
    public void onOpen(Session session) throws UnsupportedEncodingException {
        // users.add(session);
        System.out.println(session.toString());
        String name = URLDecoder.decode(session.getQueryString(), "UTF-8");
        name = name.substring(name.lastIndexOf("=") + 1);
        Map<String, Object> userProperties = session.getUserProperties();
        userProperties.put("name", name);
        chatMap.put(name, session);
        System.out.println(name + "和前端建立连接...");
    }

    @OnClose
    public void onClose(Session session) {
        // users.remove(session);
        Map<String, Object> userProperties = session.getUserProperties();
        chatMap.remove(userProperties.get("name"));
        System.out.println("断开连接");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("message: " + message);
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> userProperties = session.getUserProperties();
        try {
            Map map = mapper.readValue(message, Map.class);
            String s = (String) map.get("user");
            if (!StringUtils.isEmpty(s)) {
                Session user = chatMap.get(s);
                if (user == null) {
                    session.getBasicRemote().sendText("用户不在线");
                    return;
                }
                session.getBasicRemote().sendText(userProperties.get("name") + ": " + map.get("message"));
                user.getBasicRemote().sendText(userProperties.get("name") + ": " + map.get("message"));
                Map<String, String> info = new HashMap<>();
                info.put("name", (String) userProperties.get("name"));
                info.put("message", (String) map.get("message"));
                String s1 = JSONObject.toJSONString(info);
                staffService.sendMes(s1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

           /* for (Session user : users) {
                Map<String, Object> userProperties = session.getUserProperties();
                user.getBasicRemote().sendText(userProperties.get("name") + ":  " + message);
            }*/

    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("");
    }
}
